<template>
    <div>
        <!-- 商品分类 -->
        <nav-bar>
            <!-- 有具名 -->
            <!-- <template v-slot:left>&lt;</template>   -->
            <template v-slot:default>商品分类</template>
            <!--默认-->
        </nav-bar>
        <!-- 商品分类 -->

        <div id="mainbox">
            <!-- 排序star -->
            <div class="ordetab">
                <van-tabs v-model="active" @click="tabClick" >
                    <van-tab title="销量排序"></van-tab>
                    <van-tab title="价格排序"></van-tab>
                    <van-tab title="评化排序"></van-tab>
                </van-tabs>
            </div>
            <!-- 排序end -->
            <!-- 菜单部分star -->
                <van-sidebar class="leftmenu" v-model="activeKey">
                    <van-collapse v-model="activeName" accordion>
                        <van-collapse-item v-for="(item, index) in categroy.slice(0,5)"
                            :key="item.id"
                            :title="item.name" 
                            :name="item.name">
                            <!-- 通过下拉菜单得到商品 -->
                            <van-sidebar-item 
                                v-for="sub in item.children"
                                :title="sub.name"
                                :key="sub.id"
                                @click="getGoods(sub.id)"
                            />

                        </van-collapse-item>
                    </van-collapse>
                </van-sidebar>
            <!-- 菜单部分end -->
            <!-- 列表star -->
            <div class="goodslist">
                <div class="content">
                    <van-card
                    v-for="item in showGoods" :key="item.id"
                    @click="itemClick(item.id)"
                    :num="item.comments_count"
                    :tag="item.comments_count >= 0 ? '流行' : '标签'"
                    :price="item.price"
                    :desc="item.updated_at"
                    :title="item.title"
                    :thumb="item.cover_url"
                    :lazy-load="true"
                    />
                </div>
            </div>
            <!-- 列表end -->
        </div>
        <back-top @bTop="bTop" v-show="isShowBackTop"></back-top>
    </div>
</template>

<script>
import NavBar from "components/common/navbar/NavBar";
import BackTop from 'components/common/backtop/BackTop';
import {ref, reactive, onMounted, computed, watchEffect, nextTick} from "vue"
import {useRouter} from 'vue-router'
import {getCategory, getCategoryGoods} from "network/category"
//引入better-scroll
import BScroll from 'better-scroll';

    export default {
        name: "Categroy",
        setup() {
            //引入路由
            const router = useRouter();

            // 默认情况下可以第一个标签
            let active = ref(1);
            //activeKey为字符串格式
            let activeKey = ref(0);
            // activeName为字符串格式
            let activeName = ref(1);

            let isShowBackTop = ref(false)

            //数据模型
            const goods = reactive({
                sales: {page: 1, list: []},
                price: {page: 1, list: []},
                comments_count: {page: 1, list: []},
            })
            //通过计算属性计算返回具体的值
            const showGoods = computed(() => {
                // currentOrder.value 等于 'sales', 'price', 'comments_count'
                return goods[currentOrder.value].list;
            })

            //当前的排序是 sales 还是 price 或者 comments_count
            let currentOrder = ref('sales')
            //当前的分类ID
            let currentCid = ref(0);

            //保存分类数据的变量
            let categroy = ref([]);

            const init = () => {
                getCategoryGoods('sales', currentCid.value).then(res=>{
                    goods.sales.list = res.goods.data
                })
                getCategoryGoods('price', currentCid.value).then(res=>{
                    goods.price.list = res.goods.data
                })
                getCategoryGoods('comments_count', currentCid.value).then(res=>{
                    goods.comments_count.list = res.goods.data
                })
            }

            let bscroll = reactive({});

            //用onMounted钩子函数来获取数据
            onMounted(() => {
                //获取 分类数据
                getCategory().then(res=>{
                    categroy.value = res.categories;
                    // console.log(res);
                })

                init();

                // 创建BetterScroll对象
                bscroll = new BScroll(document.querySelector('.goodslist'), {
                    probeType: 3,  // 0, 1, 2, 3, 3 只要在运动就触发scroll事件  probe侦测滚动的位置
                    click: true, // 是否允许点击
                    pullUpLoad: true //上拉加载更多， 默认是false
                });

                //注册滚动事件
                bscroll.on('scroll', (position)=>{
                    isShowBackTop.value = (-position.y) > 300
                })

                //上拉加载数据，触发pullingUp
                bscroll.on("pullingUp", () => {
                    console.log('上拉加载更多...');
                    const page = goods[currentOrder.value].page + 1;

                    getCategoryGoods(currentOrder.value, currentCid.value).then(res=>{
                        goods[currentOrder.value].list.push(...res.goods.data);
                        goods[currentOrder.value].page += 1;
                    })

                    // 完成上拉， 等数据请求完成， 要将新数据展示出来
                    bscroll.finishPullUp();
                    //重新计算高度
                    bscroll.refresh();
                    console.log("contentheight:"+document.querySelector('.content').clientHeight);
                    console.log("当前类型:" +currentOrder.value+"，当前页："+ page);
                })
            })

            // 排序选项卡的点击事件 获取 id
            const tabClick = (index) =>{
                let orders = ['sales', 'price', 'comments_count'];
                currentOrder.value = orders[index];
                getCategoryGoods(currentOrder.value, currentCid.value).then(res=>{
                    goods[currentOrder.value].list = res.goods.data;
                    nextTick(()=>{
                    //重新计算高度
                    bscroll && bscroll.refresh();
                    })
                })
                console.log('分类的id：' +currentCid.value);
                console.log('排序的序号：' +currentOrder.value);
            }
            //通过分类得到商品的点击事件 获取 id
            const getGoods = (cid) => {
                // console.log(cid);
                currentCid.value = cid;
                init();
                console.log('分类的id：' +currentCid.value);
                console.log('排序的序号：' +currentOrder.value); 
            }

            //监听任何一个变量有变化
            watchEffect(()=>{          //nextTick 页面和数据渲言完就执行这个方法
                nextTick(()=>{
                    //重新计算高度
                    bscroll && bscroll.refresh();
                })
            })

            const bTop = () => {
                bscroll.scrollTo(0, 0, 300)
            }

            const itemClick = (id) => {
                router.push({path: '/detail', query:{id}})
            }

            return {
                activeKey,
                categroy,
                activeName,
                active,
                tabClick,
                currentOrder,
                currentCid,
                getGoods,
                goods,
                showGoods,
                bscroll,
                isShowBackTop,
                bTop,
                itemClick
            }
        },
        components: {
            NavBar,
            BackTop
        }
    }
</script>

<style scoped lang="scss">
    #mainbox {
        margin-top: 45px;
        display: flex;
        .ordetab {
            flex: 1;
            height: 50px;
            position: fixed;
            top: 45px;
            right: 0;
            left: 130px;
            cursor: not-allowed;

        }

        .leftmenu {
            position: fixed;
            top: 95px;
            left: 0;
            width: 130px;
        }

        .goodslist {
            flex: 1;
            position: absolute;
            top: 100px;
            left: 130px;
            right: 0;
            height: 100vh;
            padding: 10px;
            text-align: left !important;
        }
    }
.van_card_thumb {
    width: 68px !important;
}
</style>